package com.demo.interceptor;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.demo.common.constant.DictKeys;
import com.demo.common.model.AuthUser;
import com.demo.utils.StrUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

public class AdminUserInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation ai) {
		HttpServletRequest request = ai.getController().getRequest();
		HttpSession session = ai.getController().getSession();
		String namePwd = ai.getController().getCookie(DictKeys.COOKIE_ADMIN_TOKEN);
		AuthUser authUser = (AuthUser) session.getAttribute(DictKeys.SESSION_ADMIN_USER);
		//当用户名和密码为空时 
		if(StrUtil.isBlank(namePwd)&& authUser!=null){
			ai.getController().setCookie(DictKeys.COOKIE_ADMIN_TOKEN
					,StrUtil.getDecryptToken(authUser.getUsername()+"@&@"+authUser.getPassword()),30 * 60 * 60 * 24);
		}else if(!StrUtil.isBlank(namePwd)&&authUser==null){ //当用户名和密码不为空时
			String[] strings = StrUtil.getEncryptionToken(namePwd).split("@&@");
			authUser = AuthUser.me.login(strings[0], strings[1]);
			session.setAttribute(DictKeys.SESSION_ADMIN_USER, authUser);
		}
		//当用户名和密码为空  且   session为空时
		if(StrUtil.isBlank(namePwd)&& authUser==null){
			String uri = request.getRequestURI();
			String param = "";
			if(request.getQueryString()!=null){
				try {
					param = new String(request.getQueryString().getBytes("ISO8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			if(param.equals("")){
				uri += "?"+param;
			}
			session.setAttribute(DictKeys.ADMIN_BEFORE_URL, uri);
			ai.getController().render("/admin/login.html");
		//ai.getController().redirect(DictKeys.getBaseUrl());
		}else{
			ai.invoke();//放行
		}
		
		
	}

}
